package dating.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dating.model.User;


/**
 * Servlet implementation class Login
 */
@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends Application {
	private static final long serialVersionUID = 1L;

	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		render("login.jsp", request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 String username = request.getParameter("username");	
	   	 String password = request.getParameter("password");
	   	 boolean result = authenticate(username, password);
	   	 User user = userService.findUserByUsername(username);
	   	 if(result == true){
	   		 request.getSession().setAttribute("user_id", user.getId());		
	   		 response.sendRedirect("users");
	   	 }
	   	 else{
	   		 response.sendRedirect("login");
	   	 }
	}
	
//	private boolean isValidLogin(String username, String password) {
//		if ((username != null) && (password != null)) {
//			username = username.trim();
//			password = password.trim();
//			userService.findUserByUsername(username);
//			if ((username.length() > 0) && (password.length() > 0)) {
//				return true;
//			}
//		}
//		
//		return false;
//	}
	
	@Override
	public String getServletInfo() {
		 return "Short description";
	}
	
	private boolean authenticate(String username, String password) {
		User user = userService.findUserByUsername(username);
		if (user != null && user.getUsername().equals(username)
				&& user.getPassword().equals(password)) {
			return true;
		} else {
			return false;
		}
	}


}
